<template>
  <t-dialog
    title="新建局部铺码"
    height="650px"
    :visible="visible"
    :bodyScrollY="true"
    @onClickFooterButton="onClickFooterButton"
  >
    <el-form ref="form" label-position="top" :model="form" :rules="rules">
      <el-form-item label="项目名称：" prop="name">
        <el-input v-model="form.name" placeholder="请输入项目名称"></el-input>
      </el-form-item>
      <el-form-item label="选择Key文件：" prop="keyFile">
        <div class="w-full">
          <div class="flex pb-2">
            <span>手写码Key：</span>
            <el-upload
              ref="writecode"
              accept=".tmx"
              action=""
              :show-file-list="false"
              :before-upload="beforeUploadTMXSuffixFile"
              :http-request="getHandwrittenCodeKey"
              :limit="1"
              ><el-button slot="trigger" size="small" type="primary">
                选择文件
              </el-button>
            </el-upload>
          </div>
          <el-descriptions
            :style="{ 'margin-bottom': '18px' }"
            :labelStyle="{ 'text-align': 'center' }"
            :column="5"
            border
            direction="vertical"
            size="mini"
          >
            <el-descriptions-item
              label="SID"
              :contentStyle="{ 'text-align': 'center' }"
            >
              {{ form.keyFile.writecode.sid }}
            </el-descriptions-item>
            <el-descriptions-item
              label="OID"
              :contentStyle="{ 'text-align': 'center' }"
            >
              {{ form.keyFile.writecode.oid }}
            </el-descriptions-item>
            <el-descriptions-item
              label="BID"
              :contentStyle="{ 'text-align': 'center' }"
            >
              {{ form.keyFile.writecode.bid }}
            </el-descriptions-item>
            <el-descriptions-item
              label="PageID"
              :contentStyle="{ width: '20%', 'text-align': 'center' }"
            >
              {{ form.keyFile.writecode.minPid }}-{{
                form.keyFile.writecode.maxPid
              }}
            </el-descriptions-item>
            <el-descriptions-item
              label="有效期"
              :contentStyle="{ width: '30%', 'text-align': 'center' }"
            >
              {{ form.keyFile.writecode.expiryDate }}
            </el-descriptions-item>
          </el-descriptions>
          <div class="flex pb-2">
            <span>点读码Key：</span>
            <el-upload
              ref="readcode"
              accept=".tmxe"
              action=""
              :show-file-list="false"
              :before-upload="beforeUploadTMXESuffixFile"
              :http-request="getPointReadCodeKey"
              :limit="1"
              ><el-button slot="trigger" size="small" type="primary">
                选择文件
              </el-button>
            </el-upload>
          </div>
          <el-descriptions
            :style="{ 'margin-bottom': '18px' }"
            :labelStyle="{ 'text-align': 'center' }"
            :column="6"
            border
            direction="vertical"
            size="mini"
          >
            <el-descriptions-item
              label="SA"
              :contentStyle="{ 'text-align': 'center' }"
            >
              {{ form.keyFile.readcode.sa }}
            </el-descriptions-item>
            <el-descriptions-item
              label="SB"
              :contentStyle="{ 'text-align': 'center' }"
            >
              {{ form.keyFile.readcode.sb }}
            </el-descriptions-item>
            <el-descriptions-item
              label="SC"
              :contentStyle="{ 'text-align': 'center' }"
            >
              {{ form.keyFile.readcode.sc }}
            </el-descriptions-item>
            <el-descriptions-item
              label="SD"
              :contentStyle="{ 'text-align': 'center' }"
            >
              {{ form.keyFile.readcode.sd }}
            </el-descriptions-item>
            <el-descriptions-item
              label="index"
              :contentStyle="{ width: '20%', 'text-align': 'center' }"
            >
              {{ form.keyFile.readcode.minIndex }}-{{
                form.keyFile.readcode.maxIndex
              }}
            </el-descriptions-item>
            <el-descriptions-item
              label="有效期"
              :contentStyle="{ width: '30%', 'text-align': 'center' }"
            >
              {{ form.keyFile.readcode.expiryDate }}
            </el-descriptions-item>
          </el-descriptions>
        </div>
      </el-form-item>
      <el-form-item label="上传PDF文件" prop="pdfUrl">
        <el-upload
          ref="uploadPdf"
          accept=".pdf"
          action=""
          :before-upload="beforeUploadPDFFile"
          :http-request="uploadPDFFile"
          :disabled="uploadPDFFileDisabled"
          :limit="1"
        >
          <el-button
            slot="trigger"
            size="small"
            type="primary"
            @click="onClickUploadPdfButton"
            >上传PDF文件
          </el-button>
        </el-upload>
      </el-form-item>
    </el-form>
  </t-dialog>
</template>

<script>
import TDialog from "@/components/TDialog.vue";
import { createStore, addStoreValue } from "@/common/indexedDB";
//import oss from "@/common/ali-oss";
import {
  getCurrentTime,
  loading,
  getPDFData,
  getWriteKey,
  getReadKey,
  checkPDFFileType,
  generateProject,
} from "@/common/utils";
export default {
  components: { TDialog },
  data() {
    // key文件验证
    const keyFileCustomValidate = (rule, value, callback) => {
      if (!value.readcode.value && !value.writecode.value) {
        this.uploadPDFFileDisabled = true;
        return callback(new Error("最少上传一个Key文件"));
      }
      let currentDate = Date.now();
      let writecodeDate, pointReadCodeDate;
      // 判断是否都过期
      if (value.writecode.value && value.readcode.value) {
        writecodeDate = new Date(value.writecode.expiryDate).getTime();
        pointReadCodeDate = new Date(value.readcode.expiryDate).getTime();
        if (writecodeDate < currentDate && pointReadCodeDate < currentDate) {
          this.uploadPDFFileDisabled = true;
          return callback(new Error("手写码与点读码key都已过期！"));
        }
      }
      if (value.writecode.value) {
        writecodeDate = new Date(value.writecode.expiryDate).getTime();
        if (writecodeDate < currentDate) {
          this.uploadPDFFileDisabled = true;
          return callback(new Error("手写码key已过期！"));
        }
      }
      if (value.readcode.value) {
        pointReadCodeDate = new Date(value.readcode.expiryDate).getTime();
        if (pointReadCodeDate < currentDate) {
          this.uploadPDFFileDisabled = true;
          return callback(new Error("点读码key已过期！"));
        }
      }
      this.uploadPDFFileDisabled = false;
      return callback();
    };
    return {
      visible: false,
      uploadPDFFileDisabled: true,
      pdfMaxPageNums: "", //pdf最大页数
      // 创建项目弹窗
      form: {
        name: "",
        pdfName: "", // pdf名称
        pdfUrl: "", // pdf文件地址
        keyFile: {
          // 手写码
          writecode: {
            value: "",
            sid: 0,
            oid: 0,
            bid: 0,
            minPid: 0,
            maxPid: 0,
            expiryDate: "0/0/0",
          },
          // 点读码
          readcode: {
            value: "",
            sa: 0,
            sb: 0,
            sc: 0,
            sd: 0,
            minIndex: 0,
            maxIndex: 0,
            expiryDate: "0/0/0",
          },
        },
      },
      rules: {
        name: [
          {
            required: true,
            message: "请输入项目名称",
            trigger: "blur",
          },
        ],
        keyFile: [
          {
            required: true,
            validator: keyFileCustomValidate,
            trigger: "blur",
          },
        ],
        pdfUrl: [
          {
            required: true,
            message: "请上传PDF文件",
            trigger: "blur",
          },
        ],
      },
    };
  },
  methods: {
    open() {
      this.visible = true;
    },
    // 验证手写码文件
    beforeUploadTMXSuffixFile(file) {
      const fileName = file.name;
      const fileType = fileName
        .slice(fileName.lastIndexOf(".") + 1)
        .toLocaleUpperCase();
      if (fileType !== "TMX") {
        this.$message.warning("请上传tmx类型的文件");
        return false;
      }
      return true;
    },
    // 读取手写码Key
    async getHandwrittenCodeKey(file) {
      this.form.keyFile.writecode = await loading({
        text: "读取手写码Key文件中...",
        fn: async () => await getWriteKey(file),
      });
      //验证表单中 writecode
      this.$refs.form.validateField("keyFile");
      this.$refs.writecode.clearFiles();
    },
    // 验证点读码文件
    beforeUploadTMXESuffixFile(file) {
      const fileName = file.name;
      const fileType = fileName
        .slice(fileName.lastIndexOf(".") + 1)
        .toLocaleUpperCase();
      if (fileType !== "TMXE") {
        this.$message.warning("请上传tmxe类型的文件");
        return false;
      }
      return true;
    },
    // 读取点读码Key
    async getPointReadCodeKey(file) {
      this.form.keyFile.readcode = await loading({
        text: "读取手写码Key文件中...",
        fn: async () => await getReadKey(file),
      });
      //验证表单中 writecode
      this.$refs.form.validateField("keyFile");
      this.$refs.readcode.clearFiles();
    },
    // 点击上传PDF按钮
    onClickUploadPdfButton() {
      this.$refs.form.validateField("keyFile");
    },
    // 上传PDF之前
    async beforeUploadPDFFile(file) {
      if (!checkPDFFileType(file)) {
        this.$message.warning("请上传pdf类型的文件");
        return Promise.reject();
      }
      // 获取页码数
      const { numPages } = await loading({
        text: "读取PDF文件中...",
        fn: async () => await getPDFData(file),
      });
      if (numPages > 256) {
        this.$message.warning("PDF文件页码超过256页");
        return Promise.reject();
      }
      if (numPages > this.form.keyFile.writecode.maxPid) {
        this.$message.warning("PDF文件页码超出Key中PageId范围");
        return Promise.reject();
      }
      return Promise.resolve();
    },
    // 上传PDF文件
    async uploadPDFFile(file) {
      const reader = new FileReader();
      reader.onload = (e) => {
        const blob = new Blob([e.target.result], { type: file.file.type });
        const url = URL.createObjectURL(blob);
        this.form.pdfName = file.file.name;
        this.form.pdfUrl = url;
        this.$message.success(`${this.form.pdfName}上传成功`);
        this.$refs.form.validateField("pdfUrl");
      };
      reader.readAsArrayBuffer(file.file);
      this.$refs.uploadPdf.clearFiles();
    },
    // 点击创建项目弹窗底部按钮
    onClickFooterButton(name) {
      switch (name) {
        case "取消": {
          this.visible = false;
          break;
        }
        case "确定": {
          this.submit();
          break;
        }
      }
    },
    // 提交
    async submit() {
      // 表单校验
      const valid = await new Promise((resolve) =>
        this.$refs.form.validate(resolve)
      );
      // 校验不通过
      if (!valid) return;
      const project = {
        // 项目名称
        name: this.form.name,
        // 当前页
        currentPage: 1,
        //pdf缩放比例
        scale: 1,
        // PDF
        pdf: { name: this.form.pdfName, url: this.form.pdfUrl },
        // 手写码key
        writecode: this.form.keyFile.writecode.value
          ? this.form.keyFile.writecode
          : null,
        // 点读码key
        readcode: this.form.keyFile.readcode.value
          ? this.form.keyFile.readcode
          : null,
        // 创建时间
        createTime: getCurrentTime(),
        // 更新时间
        updateTime: getCurrentTime(),
      };
      // 生成项目
      const result = await generateProject(project);
      console.log("创建项目", result);
      if (result.code !== 200) {
        return this.$message.error("项目创建失败，请重试！");
      }
      this.$router.push(`/local/${project.name}`);
    },
  },
};
</script>